package com.jk.dmconsumer.controller;

import com.alipay.api.AlipayApiException;
import com.alipay.api.AlipayClient;
import com.alipay.api.DefaultAlipayClient;
import com.alipay.api.request.AlipayTradePagePayRequest;
import com.jk.dmcommon.entity.OrderEntity;
import com.jk.dmconsumer.service.paymentService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.mongodb.core.MongoTemplate;
import org.springframework.data.mongodb.core.query.Criteria;
import org.springframework.data.mongodb.core.query.Query;
import org.springframework.data.mongodb.core.query.Update;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.security.SecureRandom;
import java.util.UUID;

/**
 * 文件名称:PaymentController
 *
 * @Description //TODO $
 * @Date $ $
 * 作者 郭英杰
 * Copyright (c) 2021, yuxy123@gmail.com All Rights Reserved.</pre>
 */
@RestController
@RequestMapping("payment")
public class PaymentController {

    @Autowired
    private MongoTemplate mongoTemplate;

    @Autowired
    private paymentService paymentService;
    //AppId
    private final String APP_ID = "2021000118613587";
    //私钥
    private final String APP_PRIVATE_KEY = "MIIEvAIBADANBgkqhkiG9w0BAQEFAASCBKYwggSiAgEAAoIBAQCFWOwJ5zZpJXX40yDwU+GUL4KQHgrbx0pL/Up4YcPRsZ+anse3LsqzlsVbghdJtjeEkNMblIjLZSUVUuMDwasje4YNyscFA+PqOc90+nR8udRD++FzJ7TWTeGWFT6N8jq5EdhvAdkzV7BN/+meY0+ppWtNmpo/0CEoQx8l+fj3O7SOtYtmGyHeD5uRaTVMFNAhXzm5am6WHYqBJkUdOV5XL/12TjU3/G3eADi0yWPtCFtKSFNsIFZunq0k5k/CIrq/5Y3CObmOiitHrV/guGede3t2Zau6C51YXOEZYDnSdnhZYnSF3gdL5pi1GZ2KXWTuI5+SK6fbcKELniMW23wBAgMBAAECggEAaAT0o8kELcN2InL3x+F3H3RsQeXdjJIKh/p/BCcnbMVFfoULv/61SqB7NaXmaq7E4hlj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Z8cx/1k9xslNiJAbt8s5Sq2GA10uw2X2sPeyyBjy/X0ArSfEFHZTTp2fxv9XVjq6qhzYhPYMHRFPNImEeJcS/KQ==";
    private final String CHARSET = "UTF-8";
    //公钥MIIBIjANBgkqhkiG9w0BAQEFAAOCAQ8AMIIBCgKCAQEAs
    private final String ALIPAY_PUBLIC_KEY = "MIIBIjANBgkqhkiG9w0BAQEFAAOCAQ8AMIIBCgKCAQEAqnTJa7piMnkpnwGQnNtlpk3B35AwvofBFiGWxTlrz6usN9HMsmW7u92KnXNBVsf8hsRs3qXkubixz4kF1outK7Hd15Tw791V9ledGOPczT1MZpSAgKoZT2mFAmxrHaiK6LG92Q7rhSNnVGXCjlPhwcZKLacX7/BeyylgA6GArCQWCFcSHNhIvtGgGC2G8FU8Q+wbtcsfe6GYAk4GsVhZQhXVKqwo3I6x47PGz8fa+ZyjXiJMCUYo0Um2n3aH0KsJCqFYhvZjwmp9bAcDDVjw8c71shebqh/HX/T3gT5zZG0mjU97ZnXd8Plj2OuBVFDHcYW1FP2F5FbNvHV3rf5fhQIDAQAB";
    //这是沙箱接口路径,正式路径为https://openapi.alipay.com/gateway.do
    private final String GATEWAY_URL ="https://openapi.alipaydev.com/gateway.do";
    private final String FORMAT = "JSON";
    //签名方式
    private final String SIGN_TYPE = "RSA2";
    //支付宝异步通知路径,付款完毕后会异步调用本项目的方法,必须为公网地址
    private final String NOTIFY_URL = "http://localhost/";
    //付款完毕后跳转的页面

    private final String RETURN_URL = "http://localhost:7001/search";


    @RequestMapping("aliapy")
    public void alipay(HttpServletResponse httpResponse,Double price,String id) throws IOException {
        if (id != null){

       Query query = new Query();
        query.addCriteria(Criteria.where("id").is(id));
        Update update = new Update();
        update.set("orderCondition",1);
        mongoTemplate.upsert(query,update, OrderEntity.class);

        }else {



        SecureRandom r= new SecureRandom(); 
        //实例化客户端,填入所需参数
        AlipayClient alipayClient = new DefaultAlipayClient(GATEWAY_URL, APP_ID, APP_PRIVATE_KEY, FORMAT, CHARSET, ALIPAY_PUBLIC_KEY, SIGN_TYPE);
        AlipayTradePagePayRequest request = new AlipayTradePagePayRequest();
        //在公共参数中设置回跳和通知地址
        request.setReturnUrl(RETURN_URL);
        request.setNotifyUrl(NOTIFY_URL);

        //商户订单号，商户网站订单系统中唯一订单号，必填
        //生成随机Id
        String out_trade_no = UUID.randomUUID().toString();
        //付款金额，必填
        String total_amount =Double.toString(price);
        //订单名称，必填
        String subject ="大麦订单";
        //商品描述，可空
        String body = "尊敬的会员欢迎购买";
        request.setBizContent("{\"out_trade_no\":\""+ out_trade_no +"\","
                + "\"total_amount\":\""+ total_amount +"\","
                + "\"subject\":\""+ subject +"\","
                + "\"body\":\""+ body +"\","
                + "\"product_code\":\"FAST_INSTANT_TRADE_PAY\"}");
        String form = "";
        try {
            form = alipayClient.pageExecute(request).getBody(); // 调用SDK生成表单
        } catch (AlipayApiException e) {
            e.printStackTrace();
        }
        httpResponse.setContentType("text/html;charset=" + CHARSET);
        httpResponse.getWriter().write(form);// 直接将完整的表单html输出到页面
        httpResponse.getWriter().flush();
        httpResponse.getWriter().close();
    }
    }

    @RequestMapping("ces")
     public void ces(){

     paymentService.ces();
    }
}
